<?php

namespace control;
/*
*账套类
*/

class companyClass extends adIndexClass
{
    private const page = 'company';
    private const table = 'company';
    private const title = '账套';
    public static array $accountingRule;

    public function __construct()
    {
        parent::__construct();
        self::$accountingRule = ['smallEnterpriseRule' => L('finance.table.smallEnterpriseRule'), 'enterpriseRule' => L('finance.table.enterpriseRule')];
    }

    /**
     * 返回会计准则名称或键
     * @param int $nameOrKey 1：返回键/0:返回名字
     * @return string
     */
    public static function returnRule($nameOrKey = 0): string
    {
        $company = query('company', "coid = '" . self::$coid . "'");
        if (empty($company['coid'])) {
            return L('finance.table.wzdzt');
        }
        return $nameOrKey === 0 ? self::$accountingRule[$company['rule']] : $company['rule'];
    }

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            text(array("name" => "name", "title" => L('finance.table.ztmc')));
        //返回
        return $this->homeFun($this->search($html));
    }

    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),//标签
        );
        //全等查询数组
        $equal = array();

        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal));
        $page = $this->page(array("table" => self::table, "where" => $where, 'pageNum' => 10, "order" => "time desc"));
        //获取表头
        //获取记录
        $root = root;
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = [$checkAll, '名称', '会计准则', '启用时间', '纳税性质', '凭证审核', '查看范围', '负责会计', '创建时间'];
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['coid']),
                "edit" => array("title" => '编辑', "click" => "layer('company','edit',{id:'{$array['coid']}'})"),
            );
            $range = componentClass::showSelector($array['selector']);
            $range = $range ?: L('finance.table.quan_bu');
            $array['rule'] = self::$accountingRule[$array['rule']];
            $auditText = $array['isAudit'] ? L('finance.table.xu_yao_shen_he') : L('finance.table.bxysh');
            $sign ='';
            if ($array['coid'] == self::$coid){
                $sign  =$this->nowCoid();
            }
            $tr[] = [$this->dominate($dominate), "<span class='comapny-name' onclick=\"changeCoid('{$array['coid']}')\">{$array['name']}</span>".$sign, $array['rule'], $array['startDate'], $array['taxType'], $auditText, $range, self::findStaff($array['managerId']), $array['time']];
        }

        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>" . L('finance.table.add') . "</span>\n ";

        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('finance.table.shan_chu') . "</span>\n";
        }
        if ($this->power(self::page, "delAll")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delAll'})\">" . L('finance.table.emptyStr') . "</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) .$this->style().$this->js(). "</form>" . clear . $page['button'] . clear;
        return json_encode($json, 320);
    }
    public function nowCoid(){
        return <<<eof
<span class="active-coid">当前账套</span>
eof;

    }
    /*客户列表-查询结果*/
//    public function homeSearch()
//    {
//        //like查询数组
//        $like = array(
//            "name" => $this->post('name'),//标签
//        );
//        //全等查询数组
//        $equal = array();
//
//        //获取查询结果
//        $where = search(array("like" => $like, "=" => $equal));
//        $page = $this->page(array("table" => self::table, "where" => $where, 'pageNum' => 10, "order" => "time desc"));
//        //获取表头
//        //获取记录
//        $html = "<ul class='tag-list-ul'>";
//        $root = root;
//        foreach ($page['array'] as $array) {
//            $creatName = self::findStaff($array['stid']);
//            $style = '';
//            if ($array['coid'] == self::$coid) {
//                $style = "display:block";
//            }
//            $box = "<input name=\"listId[]\" type=\"checkbox\" value=\"$array[coid]\">";
//            $del = '';
//            if ($array['isDel']) {
//                $del = <<<efo
//<img alt="" onclick="layer('company','operate',{act:'del',id:'{$array['coid']}'})" src="{$root}img/control/delete.svg">
//efo;
//
//            }
//            $range = componentClass::showSelector($array['selector']);
//            $range = $range ?: L('finance.table.quan_bu');
//            $array['rule'] = self::$accountingRule[$array['rule']];
//            $auditText = $array['isAudit'] ? L('finance.table.xu_yao_shen_he') : L('finance.table.bxysh');
//            $tip = L('finance.table.ksjqhzt');
//            $html .= <<<efo
//<li>
//     <div class="tag-contain" ondblclick="changeCoid('{$array['coid']}')">
//           <div class="used-ico" style="{$style}">当前账套</div>
//           <div class="tag-contain-title">
//                 {$box}
//                 <span class="tag-contain-title-text">{$array['name']}</span>
//           </div>
//           <div class="tag-contain-body" title='$tip'>
//                 <ul class="tag-contain-ul">
//                     <li>会计准则：{$array['rule']}</li>
//                     <li>启用时间：{$array['startDate']}</li>
//                     <li>纳税性质：{$array['taxType']}</li>
//                     <li>凭证审核：{$auditText}</li>
//                     <li>查看范围：{$range}</li>
//                 </ul>
//           </div>
//           <div class="tag-contain-foot">
//                <span>{$creatName}</span>
//                <span>{$array['time']}</span>
//           </div>
//           <div class="tag-edit-content">
//                $del
//                <img onclick="layer('company','edit',{id:'{$array['coid']}'})" alt="" src="{$root}img/control/edit.svg">
//           </div>
//     </div>
//</li>
//efo;
//        }
//        $html .= <<<efo
//</ul>
//efo;
//        $html .= $this->style() . $this->js();
//
//        //控件
//        $button = "";
//        if ($this->power(self::page, "edit")) {
//            $button .= "<span onclick=\"layer('" . self::page . "','edit',{id:'" . suiji() . "'})\" class='spanButton'>" . L('finance.table.add') . "</span>\n ";
//
//        }
//        if ($this->power(self::page, "del")) {
//            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('finance.table.shan_chu') . "</span>\n";
//        }
//        if ($this->power(self::page, "delAll")) {
//            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delAll'})\">" . L('finance.table.emptyStr') . "</span>\n";
//        }
//        //返回
//        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $html . "</form>" . clear . $page['button'] . clear;
//        return json_encode($json, 320);
//    }

    private function js(): string
    {
        return <<<eof
<script>
$("[name='listForm'] .tableMany tr").on('dblclick',function(e) {
   changeCoid($(this).find("[name='listId[]']").val());
})
function changeCoid(coid){
     if (!coid){
            msg('this account is not found','error');
        }else{
            $.post(root + "control/adIndex.html?cla=homepage&fun=updateCoid", {
                'coid': coid
            }, function (data) {
                if (data.warn == 2) {
                     window.parent.location.href = root + 'control/adIndex.html';
                } else {
                    msg(data.warn,'error');
                }
            }, "json")
        }
}
</script>
eof;
    }

    /**
     * 样式
     */
    private function style(): string
    {
        return <<<eof
<style>
.tag-contain .used-ico{display: none;position: absolute;width: 108px;height: 25px;background-color: #598CE6;color: white;line-height:25px;text-align: center;right: -24px;top:16px;transform: rotate(45deg)}
.tag-list-ul{}
.tag-list-ul>li{float: left;padding: 5px;margin: 5px}
.tag-contain{width: 298px;height: 275px;padding: 10px;border: 1px solid #d7d7d7;border-radius: 2px;position: relative;overflow: hidden}
.tag-contain-title-text{margin-left: 10px;font-weight: bold;font-size: 14px}
.tag-contain-body{margin: 10px;padding: 10px;height: 140px;overflow: auto}
.tag-contain-ul li{margin: 5px 5px}
.tag-contain-foot{margin: 10px;padding: 10px;border-bottom: 1px solid #d7d7d7}
.tag-contain-foot span:nth-child(2){float: right}
.tag-edit-content{text-align: right}
.tag-edit-content img:nth-child(2){width: 20px;cursor: pointer}
.tag-edit-content img:nth-child(1){width: 22px;cursor: pointer}
.label-edit-ul li{float: left}
.add-attr-button{border: 2px solid #6aacfb;margin-top: 5px;color: #6aacfb;font-weight: bold;font-size: 21px; width: 16px;height: 16px;text-align: center;line-height: 13px;cursor: pointer;border-radius: 2px;}
.active-coid{border: 1px solid #6aacfb;padding: 0 3px;color: #6aacfb;margin-left: 10px;border-radius: 3px;font-size: 12px}
.comapny-name:hover{text-decoration: underline;color: #6aacfb;cursor: pointer}
</style>
eof;

    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->post('id')?:suiji();
        $info = query(self::table, " coid = '" . $id . "' ");
        $readOnly = $info['coid'] ? 'disabled' : '';
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('finance.table.ztmc') . "：" => text(["name" => "name", "value" => $info['name']]),

                ],
                [
                    must . L('finance.table.ztqyny') . "：" => text(["name" => "startDate", 'laydate' => ['type' => 'month'], "value" => $info['startDate']]),
                ],
                [
                    must . L('finance.table.hui_ji_zhun_ze') . "：" => select(["name" => "rule", 'title' => L('finance.table.qing_xuan_ze'), 'class' => 'width200', 'other' => $readOnly, 'option' => ['smallEnterpriseRule' => '2013小企业会计准则'], "value" => $info['rule']]) . componentClass::tipComponent(L('finance.table.hjzzschjbnqh')),
                ],
                [
                    must . L('finance.table.zzszl') . "：" => radio(["name" => "taxType", "value" => explode('，', para('taxType')), 'checked' => $info['taxType']]),
                ],
                [
                    must . L('finance.table.pzsh') . "：" => radio(["name" => "isAudit", "value" => [1 => L('finance.table.xu_yao_shen_he'), 0 => L('finance.table.bxysh')], 'checked' => $info['isAudit'] ?: 0]),
                ],
                [
                    L('finance.table.range') . "：" => componentClass::staffSelector($info['selector']),
                ],
                [
                    L('finance.table.manager') . "：" => selectMultiple(["name" => "managerId",'where'=>"state != '离职' and workFlow = '已复核'", 'table'=>'staff','sqlId'=>'stid','sqlField'=>'name','title' => '请选择', "value" => $info['managerId']]),

                ],
                [
                    L('finance.table.taxName') . "：" => text(["name" => "invoiceCompany", 'class' => 'width300', "value" => $info['invoiceCompany']]),

                ],
                [
                    L('finance.table.taxNum') . "：" => text(["name" => "invoiceNo", 'class' => 'width300', "value" => $info['invoiceNo']]),

                ],
                [
                    L('finance.table.address') . "：" => text(["name" => "addressAndTel", 'class' => 'width300', "value" => $info['addressAndTel']]),

                ],
                [
                    L('finance.table.bank') . "：" => text(["name" => "bankName", 'class' => 'width300', "value" => $info['bankName']]),

                ],
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $info['coid'] ?:$id]),
            'button' => '<button class="button left-bottom" onclick="subForm(\'' . self::page . 'EditForm\',root+\'control/adIndex.html?cla=' . self::page . '&fun=editEdit\')">' . L('finance.table.bao_cun') . '</button>',
        ]);
        //返回
        return $this->layer(array("title" => L('setting.table.edit'), "height" => 700, 'width' => 900, "html" => $html));
    }


    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $where = " coid = '$id' ";
        $info = query(self::table, $where);
        $field = [
            "name" => $this->post('name'),
            "startDate" => $this->post('startDate'),
            "rule" => $this->post('rule') ?: $info['rule'],
            "taxType" => $this->post('taxType'),
            "isAudit" => $this->post('isAudit'),
            "invoiceCompany" => $this->post('invoiceCompany'),
            "invoiceNo" => $this->post('invoiceNo'),
            "addressAndTel" => $this->post('addressAndTel'),
            "bankName" => $this->post('bankName'),
            'selector' => $this->post('staff')[0] ?? '',//员工选择器
            'managerId'=>$this->post('managerId')
        ];
        $staff = componentClass::returnStaffId($field['selector']);
        $field['see'] = implode(',', $staff);
        $annotation = [
            'name' => L('finance.table.ztmc'),
            'startDate' => L('finance.table.ztqyny'),
            'rule' => L('finance.table.hui_ji_zhun_ze'),
            'taxType' => L('finance.table.zzszl'),
            'isAudit' => L('finance.table.pzsh'),
        ];
        $rules = [
            'name' => 'required',
            'startDate' => 'required',
            'rule' => 'required',
            'taxType' => 'required',
            'isAudit' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('finance.table.company_edit_permission');
        } elseif (static::total(array('table' => self::table, 'where' => "name = '$field[name]' and coid !='$id'")) > 0) {
            $json['warn'] = L('finance.table.yczcmc');
        } elseif (!empty($info['id']) && $info['rule'] != $field['rule']) {
            $json['warn'] = L('finance.table.hjzzbnqh');
        } else {
            $this->startTrans();
            if (!$info['coid']) {
                $field = array_merge($field, [
                    'coid' => $id,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
//                $attrId = self::getId();
//                $bool = static::insert(["table" => 'material_attr', "field" => ['id' => $attrId, 'name' => L('finance.table.mo_ren_shu_xing'), 'coid' => $id, 'stid' => self::$stid]]);
//                if ($bool != '新增成功') {
//                    $json['warn'] = $bool;
//                }
//                $bool = static::insert(["table" => 'material_attr_detail', "field" => ['id' => self::getId(), 'value' => '-', 'coid' => $id, 'orderId' => $attrId]]);
//                if ($bool != '新增成功') {
//                    $json['warn'] = $bool;
//                }

            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }

            if (in_array($json['warn'], ['新增成功', '更新成功'])) {
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $id], L('finance.table.company_edit_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            case 'delAll':
                $act = 'del';
                $msg = L('finance.table.company_del_title');
                $title = self::page . 'DeleteAll';
                $function = 'deleteAll';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = L('finance.table.company_del_title');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('finance.table.nmzscdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('finance.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '$id' ");
                if (!$info['isDel']) {
                    //返回
                    $warn = L('finance.table.company_del_failed');
                } elseif (static::total(array('table' => "material", 'where' => "coid = '$id'")) > 0) {
                    $warn = L('finance.table.cztyzsjbnsc');
                } elseif (static::total(array('table' => "kehu", 'where' => "coid = '$id'")) > 0) {
                    $warn = L('finance.table.cztyzsjbnsc');
                } elseif (static::total(array('table' => "voucher", 'where' => "coid = '$id'")) > 0) {
                    $warn = L('finance.table.cztyzpzsjbnsc');
                } else {
                    $this->deleteTable($id, true);
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " coid = '$id' "));
                    delete(array("table" => 'material_attr', "where" => " coid = '$id' "));
                    //删除科目
                    delete(array("table" => 'subject', "where" => " coid = '$id' "));
                    //返回
                    $warn = L('finance.table.sccg');
                    $x++;
                }
                $text .= str_replace(['{{name}}', '{{id}}'], [$info['name'], $info['coid']], L('finance.table.company_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.company_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('finance.table.company_del_msg'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function deleteAll()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "delAll")) {
            $json['warn'] = L('finance.table.nmzqkdzx');
        } elseif (empty($array)) {
            $json['warn'] = L('finance.table.nygsjdmzxzn');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '$id' ");
                $this->deleteTable($id);
                //返回
                $warn = L('finance.table.emptySuccess');
                $x++;
                $text .= str_replace(['{{name}}', '{{id}}'], [$info['name'], $info['coid']], L('finance.table.company_del_text')) . $warn . "。<br>";
            }
            static::rSet('loginPage', 1);
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('finance.table.company_empty_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('finance.table.company_empty_msg'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 清空此coid的表
     */
    private function deleteTable($coid, $isAll = false)
    {
        global $conf;
        $sql = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA ='{$conf['databaseName']}' and TABLE_TYPE = 'BASE TABLE'";
        $all = self::sqlFind($sql);
        foreach ($all as $array) {
            $sql = "SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA='{$conf['databaseName']}' AND TABLE_NAME='{$array['TABLE_NAME']}'";
            $result = self::sqlFind($sql);
            $field = [];
            foreach ($result as $val) {
                $field[] = $val['COLUMN_NAME'];
            }
            $whiteField = [];
            if (!$isAll) {
                $whiteField = ['business_voucher_template', 'business_voucher_template_detail', 'warehouse_type', 'option_setting', 'warehouse_position', 'tag', 'tag_detail', 'routing', 'routing', 'routing', 'routing', 'routing_detail', 'company', 'bom', 'process',
                    'team', 'team_detail', 'bom', 'bom', 'bom_detail',
                    'quarantine', 'quarantine_item', 'quarantine_reason', 'supplier', 'product_line', 'kehu', 'warehouse', 'account', 'material_attr',
                    'material', 'material_attr_detail', 'material_sku', 'material_sku_detail', 'material_type',
                    'subject', 'subject', 'subject_assist', 'currency', 'voucher_word', 'account', 'cash', 'subject_demo', 'cash_demo', 'voucher_word_demo', 'asset_debt_demo', 'asset_debt_formula_demo', 'period_end_setting_demo',
                    'period_end_setting_detail_demo', 'profit_income_demo', 'profit_income_formula_demo', 'material_attr_scheme'];
            }
            if (in_array('coid', $field, true) && !in_array($array['TABLE_NAME'], $whiteField)) {
                if (in_array($array['TABLE_NAME'], ['sale_order', 'sale_send_order', 'sale_refund_order', 'purchase_order', 'voucher', 'purchase_refund_order', 'purchase_get_order'])) {
                    //删除文件
                    $result = find(array('table' => 'file', 'where' => " targetId in (select id from {$array['TABLE_NAME']} where coid = '$coid')"));
                    foreach ($result['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array('table' => 'file', 'where' => " id = '$val[id]'"));
                    }
                }
                sqlExec("DELETE FROM `{$array['TABLE_NAME']}` WHERE coid = '$coid'");
            }
        }
    }

    /**
     * 仅保留基础数据
     */
    private function deleteAllData()
    {
        global $conf;
        $sql = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA ='{$conf['databaseName']}' and TABLE_TYPE = 'BASE TABLE'";
        $all = self::sqlFind($sql);
        foreach ($all as $array) {
            $sql = "SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA='{$conf['databaseName']}' AND TABLE_NAME='{$array['TABLE_NAME']}'";
            $result = self::sqlFind($sql);
            $field = [];
            foreach ($result as $val) {
                $field[] = $val['COLUMN_NAME'];
            }
            $whiteField = ['business_voucher_template', 'business_voucher_template_detail', 'warehouse_type', 'option_setting', 'warehouse_position', 'tag', 'tag_detail', 'routing', 'routing', 'routing', 'routing', 'routing_detail', 'company', 'bom', 'process',
                'team', 'team_detail', 'bom', 'bom', 'bom_detail',
                'quarantine', 'quarantine_item', 'quarantine_reason', 'supplier', 'product_line', 'kehu', 'warehouse', 'account', 'material_attr',
                'material', 'material_attr_detail', 'material_sku', 'material_sku_detail', 'material_type',
                'subject', 'subject', 'subject_assist', 'currency', 'voucher_word', 'account', 'cash', 'subject_demo', 'cash_demo', 'voucher_word_demo', 'asset_debt_demo', 'asset_debt_formula_demo', 'period_end_setting_demo',
                'period_end_setting_detail_demo', 'profit_income_demo', 'profit_income_formula_demo'];
            if (in_array('coid', $field, true) && !in_array($array['TABLE_NAME'], $whiteField)) {
                if (in_array($array['TABLE_NAME'], ['sale_order', 'sale_send_order', 'sale_refund_order', 'purchase_order', 'voucher', 'purchase_refund_order', 'purchase_get_order'])) {
                    //删除文件
                    $result = find(array('table' => 'file', 'where' => " targetId in (select id from {$array['TABLE_NAME']})"));
                    foreach ($result['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array('table' => 'file', 'where' => " id = '$val[id]'"));
                    }
                }
                sqlExec("DELETE FROM `{$array['TABLE_NAME']}` WHERE 1");
            } elseif (!in_array('coid', $field, true)) {
                $whiteField = ['staff', 'user', 'para', 'img', 'department', 'role', 'job', 'talent_pool', 'examine', 'log',
                    'print_template', 'subject_demo', 'cash_demo', 'voucher_word_demo', 'asset_debt_demo', 'asset_debt_formula_demo', 'period_end_setting_demo',
                    'period_end_setting_detail_demo', 'profit_income_demo', 'company', 'profit_income_formula_demo'];
                if (!in_array($array['TABLE_NAME'], $whiteField)) {
                    if (in_array($array['TABLE_NAME'], ['file', 'account_elect_file'])) {
                        //删除文件
                        $result = find(array('table' => $array['TABLE_NAME']));
                        foreach ($result['array'] as $val) {
                            fileDelete($val['src']);
                        }
                    }
                    sqlExec("DELETE FROM `{$array['TABLE_NAME']}` WHERE 1");
                }
            }
        }
    }

}

